import cv2  
import numpy as np  
import os  


# Gamma校正函数  
def gamma_correction(src, gamma):  
    lut = np.empty((1, 256), dtype=np.uint8)  
    for i in range(256):  
        lut[0, i] = np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255).astype(np.uint8)  
    # 应用LUT到图像  
    dst = cv2.LUT(src, lut)  
    return dst  
  
# 主函数  
def main():  
    # 定义输入文件夹  
    input_folder = './原始图片'  
    output_image_path = './转换图片'  # 输出拼接后的图片路径  

    try:
        for root, _, files in os.walk(output_image_path):  
            for file in files:
                os.remove(output_image_path+"/"+file)
    except:
        print("移除过期结果失败..")
    # 读取并处理所有图片，存储为列表  
    images = []  
    for filename in os.listdir(input_folder):  
        if filename.endswith('.jpg') or filename.endswith('.png'):  # 根据需要添加其他格式  
            # 读取图像  
            image_path = os.path.join(input_folder, filename)  
            #image = cv2.imread(image_path)
            image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), -1)
  
            if image is not None:  
                # 复制图像并转换为浮点数  
                src = image.copy().astype(np.float32) / 255.0  
  
                # 高斯模糊  
                gauss = cv2.GaussianBlur(src, (101, 101), 0)  
  
                # 除以高斯模糊结果  
                dst = cv2.divide(src, gauss, scale=255)  
  
                # 将结果转换为8位无符号整数  
                dst = np.clip(dst, 0, 255).astype(np.uint8)  
  
                # 应用Gamma校正  
                mat_gamma = gamma_correction(dst, 1.5)  
  
                # 将处理后的图像添加到列表中  
                images.append(mat_gamma)  
            else:  
                print(f"Error: Could not read the image {image_path}")  
  
    # 上下拼接所有图像  
    combined_image = cv2.vconcat(images)  
  
    # 保存拼接后的图像  
    #cv2.imwrite(output_image_path+"/输出.png", combined_image)
    cv2.imencode('.png', combined_image)[1].tofile(output_image_path+"/put.png")
    print(f"All images have been combined and saved to {output_image_path}")  
  
# 调用主函数  
if __name__ == '__main__':  
    main()
